package com.hui.admin.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {

    @Value("${app.secret}")
    private String secret;

    // 密钥
    private static String SECRET_KEY;

    @PostConstruct
    public void init() {
        SECRET_KEY = secret;
    }

    // 过期时间
    private static final long EXPIRATION = 3600000;

    /**
     * 生成 JWT Token
     *
     * @param username 用户名
     * @return Token
     */
    public static String generateToken(String username) {
        return JWT.create()
                .withSubject(username)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION))
                .sign(Algorithm.HMAC512(SECRET_KEY));
    }

    /**
     * 解析 JWT Token 获取用户信息
     *
     * @param token Token
     * @return 用户名
     */
    public static String parseToken(String token) {
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC512(SECRET_KEY))
                .build()
                .verify(token);
        return decodedJWT.getSubject();
    }
}

